package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.DTO.OrdersDto;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.OrdersService.Impl.OrdersImplService;
import com.itheima.reggie.service.OrdersService.OrderDetailSerivce;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.PushBuilder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {
    @Autowired
    OrdersImplService ordersImplService;
    @Autowired
    OrderDetailSerivce orderDetailSerivce;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersImplService.submit(orders);
        return R.success("下单成功");
    }

    //查询订单
    @GetMapping("/userPage")
    public R<Page> userPage(int page,int pageSize){
        Page<Orders> orderDetailPage = new  Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        ordersImplService.page(orderDetailPage,lambdaQueryWrapper);
        BeanUtils.copyProperties(orderDetailPage,ordersDtoPage,"records");
        List<Orders> records = orderDetailPage.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            Long id = item.getId();
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.in(OrderDetail::getOrderId,id);
            List<OrderDetail> list = orderDetailSerivce.list(orderDetailLambdaQueryWrapper);
            if (list != null){
                ordersDto.setOrderDetails(list);
            }
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }
}
